package win.zxshuo.www.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

/**
 * @ClassName 请求操作工具类
 * @Author liguangyao
 * @Date 2018/5/21 下午3:07
 * @Version 1.0
 **/
public class SendRequestUtils {

    // 公共请求体
    private static final String CONTENT_TYPE_APPLICATION_JSON = "application/json";
    private static final String CONTENT_TYPR_X_WWW_FORM_URLENCODED = "application/x-www-form-urlencoded";
    private static final String ACCEPT = "*/*";
    private static final String CONNECTION = "Keep-Alive";
    private static final String USER_AGENT = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)";
    private static final String CHARSET = "UTF-8";

    /**
     * HttpClient POST 请求方式
     * @param url
     * @param param
     * @param token
     * @param tokenType
     * @return
     */
    public static String sendPostHttpClient(String url, String param, String token, String tokenType){
        String result = "";
        BufferedReader in = null;
        try {
            HttpClient client = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost();
            httpPost.setURI(new URI(url));
            httpPost.addHeader("authorization" ,tokenType + " " + token);
            httpPost.addHeader("content-type",CONTENT_TYPE_APPLICATION_JSON);
            httpPost.addHeader("accept", ACCEPT);
            httpPost.addHeader("connection", CONNECTION);
            httpPost.addHeader("user-agent",USER_AGENT);
            httpPost.addHeader("charset", CHARSET);
            httpPost.setEntity(new StringEntity(param,CHARSET));
            HttpResponse httpResponse = client.execute(httpPost);
            HttpEntity entity = httpResponse.getEntity();
            result = EntityUtils.toString(entity, CHARSET);
            JSONObject jsonObject = JSONObject.parseObject(result);
            result = jsonObject.toJSONString();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            closeIOFlow(null,in);
        }
        return result;
    }

    /**
     * HttpClient GET 请求方式
     * @param url
     * @param tokenType
     * @param token
     * @return
     */
    public static String sendGetHttpClient(String url,String tokenType ,String token){
        String result = "";
        BufferedReader in = null;
        try {
            HttpClient client = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet();
            httpGet.setURI(new URI(url));
            httpGet.setHeader("authorization" ,token + " " + tokenType);
            httpGet.setHeader("content-type",CONTENT_TYPE_APPLICATION_JSON);
            httpGet.setHeader("accept", ACCEPT);
            httpGet.setHeader("connection", CONNECTION);
            httpGet.setHeader("user-agent",USER_AGENT);
            httpGet.setHeader("charset", CHARSET);
            HttpResponse httpResponse = client.execute(httpGet);
            HttpEntity entity = httpResponse.getEntity();
            result = EntityUtils.toString(entity, CHARSET);
            JSONObject jsonObject = JSONObject.parseObject(result);
            result = jsonObject.toJSONString();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            closeIOFlow(null,in);
        }
        return result;
    }

    /**
     * 原生 POST 请求方式
     * @param url
     * @return
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("content-type", CONTENT_TYPR_X_WWW_FORM_URLENCODED);
            conn.setRequestProperty("accept", ACCEPT);
            conn.setRequestProperty("connection", CONNECTION);
            conn.setRequestProperty("user-agent",USER_AGENT);
            conn.setRequestProperty("charset", CHARSET);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), CHARSET));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            closeIOFlow(out,in);
        }
        return result;
    }

    /**
     * 原生 GET 请求方式
     * @param url
     * @return
     */
    public static String sendGet(String url) {
        String result = "";
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", ACCEPT);
            connection.setRequestProperty("connection", CONNECTION);
            connection.setRequestProperty("user-agent", USER_AGENT);
            connection.setRequestProperty("charset", CHARSET);
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), CHARSET));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }finally {
            closeIOFlow(null,in);
        }

        return result;
    }

    private static void closeIOFlow(PrintWriter printWriter,BufferedReader bufferedReader){
        try {
            if(printWriter != null){
                printWriter.close();
            }
            if(bufferedReader != null){
                bufferedReader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
